<template>
  <div class="conetr h-full flex flex-col">
    <div class="center-board">
      <div class="center-title">
        <h3>材料选购</h3>
      </div>
      <div class="action-bar mb-[20px]">
        <el-button icon="Back" type="primary" plain text @click="backTo">返回</el-button>
        <el-button
          icon="Download"
          type="success"
          plain
          :disabled="!canEdit"
          :loading="loading"
          @click="handleSubmit"
        >
          保存
        </el-button>
      </div>
    </div>
    <el-button v-if="canEdit" type="primary" class="mb-[10px]" @click="handleAdd">
      新增材料信息
    </el-button>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      class="form flex flex-col flex-1 overflow-auto"
    >
      <BasePageTable
        row-key="indexs"
        :table-data="formData.tableData"
        :table-columns-data="tableColumnsData"
        height="100%"
        class="flex-1 overflow-auto"
      >
        <template #index="scoped">
          {{ scoped.index + 1 }}
        </template>
        <template #categoryId="{ row, index }">
          <el-form-item :prop="'tableData.' + index + '.categoryId'" :rules="formRules.categoryId">
            <el-cascader
              v-model="row.categoryId"
              placeholder="请选择品类"
              style="width: fit-content"
              :options="getMaterialCategoryList"
              :show-all-levels="false"
              :props="{
                value: 'id',
                label: 'name',
              }"
              :disabled="handleRowDisabled(row)"
            />
          </el-form-item>
        </template>
        <template #brandId="{ row, index }">
          <el-form-item :prop="'tableData.' + index + '.brandId'" :rules="formRules.brandId">
            <div class="flex">
              <el-select
                v-model="row.brandId"
                placeholder="请选择品牌"
                clearable
                filterable
                class="mr-2.5"
                :disabled="handleRowDisabled(row)"
                @change="handleChangeBrand($event, row)"
              >
                <el-option
                  v-for="item in brandList"
                  :key="item.id"
                  :label="item.brandName"
                  :value="item.id"
                />
              </el-select>
            </div>
          </el-form-item>
        </template>
        <template #store="{ row, index }">
          <el-form-item :prop="'tableData.' + index + '.store'" :rules="formRules.store">
            <el-input
              v-model.number.trim="row.store"
              maxlength="100"
              placeholder="请输入门店"
              :disabled="handleRowDisabled(row)"
            ></el-input>
          </el-form-item>
        </template>
        <template #buyDate="{ row, index }">
          <el-form-item :prop="'tableData.' + index + '.buyDate'" :rules="formRules.buyDate">
            <el-date-picker
              v-model="row.buyDate"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择购买日期"
              :disabled="handleRowDisabled(row)"
            />
          </el-form-item>
        </template>
        <template #contractTime="{ row, index }">
          <el-form-item
            :prop="'tableData.' + index + '.contractTime'"
            :rules="formRules.contractTime"
          >
            <el-date-picker
              v-model="row.contractTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择合同时间"
              :disabled="handleRowDisabled(row)"
            />
          </el-form-item>
        </template>
        <template #brandName="{ row, index }">
          <el-form-item :prop="'tableData.' + index + '.brandName'" :rules="formRules.brandName">
            <el-input
              v-model.trim="row.brandName"
              placeholder="请输入自定义品牌"
              maxlength="100"
              :disabled="handleRowDisabled(row)"
              @change="row.brandId = ''"
            ></el-input>
          </el-form-item>
        </template>
        <template #salesman="{ row, index }">
          <el-form-item :prop="'tableData.' + index + '.salesman'" :rules="formRules.salesman">
            <el-input
              v-model.trim="row.salesman"
              placeholder="请输入销售人员"
              maxlength="20"
              :disabled="handleRowDisabled(row)"
            ></el-input>
          </el-form-item>
        </template>
        <template #salesmanMobile="{ row, index }">
          <el-form-item
            :prop="'tableData.' + index + '.salesmanMobile'"
            :rules="formRules.salesmanMobile"
          >
            <el-input
              v-model.trim="row.salesmanMobile"
              placeholder="请输入销售人员电话"
              maxlength="20"
              :disabled="handleRowDisabled(row)"
            ></el-input>
          </el-form-item>
        </template>
        <template #couponCode="{ row }">
          {{ row.couponCode }}
        </template>
        <template #amount="{ row, index }">
          <el-form-item :prop="'tableData.' + index + '.amount'" :rules="formRules.amount">
            <el-input-number
              v-model.number.trim="row.amount"
              :min="0"
              :max="99999999"
              :disabled="handleRowDisabled(row)"
              placeholder="请输入金额"
            />
          </el-form-item>
        </template>

        <template #contractFile="{ row, index }">
          <el-form-item
            :prop="'tableData.' + index + '.contractFile'"
            :rules="formRules.contractFile"
            class="pb-2"
          >
            <div class="mult-div">
              <!-- <FilesUpload
                v-model="formData.contractFile"
                :disabled="!canEdit"
                v-model:loading="contractFileLoading"
                :limit="20"
                @uploadSuccess="validateSingle('contractFile')"
                accept=".jpeg,.png,.jpg,.bmp,.pdf"
              ></FilesUpload> -->
              <FilesUpload
                v-model="row.contractFile"
                v-model:loading="row.loading"
                :limit="5"
                :disabled="handleRowDisabled(row)"
                accept=".jpeg,.png,.jpg,.bmp,.pdf"
                @upload-success="validateSingle('tableData.' + index + '.contractFile')"
              />
            </div>
          </el-form-item>
        </template>
        <template #paymentFile="{ row, index }">
          <el-form-item
            class="pb-2"
            :prop="'tableData.' + index + '.paymentFile'"
            :rules="formRules.paymentFile"
          >
            <MultiImageUpload
              v-model="row.paymentFile"
              v-model:loading="row.loading"
              :limit="2"
              :disabled="handleRowDisabled(row)"
              @upload-success="validateSingle('tableData.' + index + '.paymentFile')"
            />
          </el-form-item>
        </template>
        <template #receiptFile="{ row, index }">
          <el-form-item
            class="pb-2"
            :prop="'tableData.' + index + '.receiptFile'"
            :rules="formRules.receiptFile"
          >
            <MultiImageUpload
              v-model="row.receiptFile"
              v-model:loading="row.loading"
              :limit="2"
              :disabled="handleRowDisabled(row)"
              @upload-success="validateSingle('tableData.' + index + '.receiptFile')"
            />
          </el-form-item>
        </template>
        <template #status="{ row, name }">
          <el-tag :type="HOUSE_STATUS.FILLED.value === row.status ? 'success' : 'info'">
            {{ getLabelByValue(HOUSE_STATUS, row.status) }}
          </el-tag>
        </template>
        <template #operation="{ row, index }">
          <el-button
            link
            icon="Edit"
            type="primary"
            :disabled="handleRCouponDisabled(row)"
            @click="handleEditConsumerCouponBudget(row)"
          >
            核销券码
          </el-button>
          <el-button
            link
            type="danger"
            icon="Delete"
            :disabled="handleRowDisabled(row)"
            @click="handleDelete(formData.tableData, index)"
          >
            删除
          </el-button>
          <!--              <el-button link type="primary" icon="Edit" @click="drawer = true">编辑</el-button>-->
        </template>
      </BasePageTable>
    </el-form>
  </div>
  <el-dialog v-model="dialogCoupon" title="核销券码" width="40%" @close="couponCloseDialog">
    <el-form
      ref="couponRef"
      :model="couponData"
      :rules="couponRules"
      label-width="150px"
      class="form"
    >
      <el-form-item label="代金券券码" prop="couponCode">
        <el-input v-model.number.trim="couponData.couponCode" placeholder="请输入代金券券码" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="couponSubmit">确 定</el-button>
        <el-button @click="couponCloseDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { useCategory } from "@/hooks/useCategory";
import { ElMessage } from "element-plus";
import { validatePhone } from "@/utils/formvalidate";
import HouseAPI, {
  ConsumerHouseConstructionMaterialBuyForm,
  ConsumerHouseConstructionMaterialInstallForm,
} from "@/api/house";
import BasePageTable from "@/components/BasePageTable/index.vue";
import MultiImageUpload from "@/components/Upload/MultiImageUpload.vue";
import FilesUpload from "@/components/Upload/FilesUpload.vue";
import { useBrand } from "@/hooks/useBand";
import { HOUSE_STATUS } from "@/enums/house/house-const";
import { getLabelByValue } from "@/utils/enums";
import couponApi from "@/api/coupon/coupon";
const { brandList } = useBrand(true);

// 1. 正确定义 props
const props = defineProps({
  // 1 是装修知识的type固定字段 2是装修案例
  status: {
    type: [String, Number],
    required: true,
    default: "",
  },
});
// const { getMaterialCategory, getMaterialCategoryList } = useCategory({
//   selfOwn: true,
// });
const { getMaterialCategory, getMaterialCategoryList } = useCategory({});

// 定义 emit，用于通知外部关闭事件
const emit = defineEmits(["update:modelValue", "loadData", "backTo"]);
const dialog = reactive({
  title: "",
  visible: false,
});
const dialogCoupon = ref(false);
const drawer = ref(false);
const loading = ref(false);
const formRef = ref();
const currentRow = ref({});
const couponData = ref({
  linkId: undefined,
  couponCode: "",
});
const couponRules = reactive({
  couponCode: [{ required: true, message: "请填写代金券券码", trigger: "blur" }],
});
const couponRef = ref();

const tableColumnsData = ref([
  {
    prop: "index",
    label: "排序",
    showOverflowTooltip: true,
    customSlot: "index",
    width: 60,
  },
  {
    prop: "store",
    label: "门店",
    showOverflowTooltip: true,
    customSlot: "store",
    width: 200,
  },
  {
    prop: "buyDate",
    label: "购买日期",
    showOverflowTooltip: true,
    customSlot: "buyDate",
    width: 200,
  },
  {
    prop: "categoryId",
    label: "品类",
    showOverflowTooltip: true,
    customSlot: "categoryId",
    width: 200,
  },
  {
    prop: "brandId",
    label: "品牌",
    showOverflowTooltip: true,
    customSlot: "brandId",
    width: 200,
  },
  {
    prop: "brandName",
    label: "自定义品牌",
    showOverflowTooltip: true,
    customSlot: "brandName",
    width: 200,
  },
  {
    prop: "couponCode",
    label: "代金券券码",
    showOverflowTooltip: true,
    customSlot: "couponCode",
    width: 140,
  },
  {
    prop: "salesman",
    label: "销售人员",
    showOverflowTooltip: true,
    customSlot: "salesman",
    width: 200,
  },
  {
    prop: "salesmanMobile",
    label: "销售人员电话",
    showOverflowTooltip: true,
    customSlot: "salesmanMobile",
    width: 200,
  },

  {
    prop: "amount",
    label: "合同金额(元)",
    showOverflowTooltip: true,
    customSlot: "amount",
    width: 200,
  },
  {
    prop: "contractTime",
    label: "合同时间",
    showOverflowTooltip: true,
    customSlot: "contractTime",
    width: 200,
  },
  {
    prop: "receiptFile",
    label: "收款凭证",
    showOverflowTooltip: true,
    customSlot: "receiptFile",
    width: 400,
  },
  {
    prop: "contractFile",
    label: "合同",
    showOverflowTooltip: true,
    customSlot: "contractFile",
    width: 300,
  },
  {
    prop: "remark",
    label: "驳回理由",
    showOverflowTooltip: true,
    width: 200,
  },
  // {
  //   prop: "paymentFile",
  //   label: "付款凭证",
  //   showOverflowTooltip: true,
  //   customSlot: "paymentFile",
  //   width: 300,
  // },

  {
    prop: "operation",
    label: "操作",
    width: 200,
    fixed: "right",
    align: "center",
    customSlot: "operation", // 自定义插槽名称
  },
]);

const defaultFormData: FormData = {
  tableData: [],
};

interface FormData {
  tableData: Array<ConsumerHouseConstructionMaterialBuyForm>;
}

const formData = ref({
  ...defaultFormData,
});
const formRules = reactive({
  categoryId: [{ required: true, message: "请选择品类", trigger: "change" }],
  amount: [{ required: true, message: "请输入合同金额", trigger: "blur" }],
  salesmanMobile: [
    { required: true, message: "请输入销售人员电话", trigger: "blur" },
    { validator: validatePhone, trigger: "blur" },
  ],
  contractTime: [{ required: true, message: "请选择合同时间", trigger: "change" }],
  contractFile: [{ required: true, message: "请上传合同", trigger: "change" }],
  paymentFile: [{ required: true, message: "请上传付款凭证", trigger: "change" }],
  receiptFile: [{ required: true, message: "请上传收款凭证", trigger: "change" }],
});
watch(
  () => formData.value.tableData,
  (newVal) => {
    loading.value = formData.value.tableData.findIndex((item) => item.loading) !== -1;
  },
  { deep: true }
);
const validateSingle = (field: string) => {
  formRef.value.validateField(field);
};
function backTo() {
  emit("backTo");
}
async function handleSubmit() {
  const validate = await formRef.value.validate();
  if (!validate || !formData.value.tableData.length) {
    ElMessage.error("请检查输入内容");
    return;
  }
  loading.value = true;
  try {
    const params = formData.value.tableData.map((item) => {
      //超过两就传最后一个
      let categoryId = item.categoryId;
      if (Array.isArray(item.categoryId) && item.categoryId.length > 0) {
        categoryId = item.categoryId[item.categoryId.length - 1];
      }
      return {
        ...item,
        contractFile: JSON.stringify(item.contractFile),
        paymentFile: JSON.stringify(item.paymentFile),
        receiptFile: JSON.stringify(item.receiptFile),
        categoryId,
      };
    });
    await HouseAPI.houseConstructionMaterialBuyEdit(params);
    ElMessage.success("成功");
    emit("loadData");
    loading.value = false;
    emit("backTo");
    handleCloseDialog();
  } catch (error) {
    console.log("error", error);
    //ElMessage.error("失败");
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  emit("update:modelValue", false); // 关闭弹窗
}
const canEdit = ref(true);

async function showModal(val, cannotEdit = false) {
  dialog.visible = true;
  currentRow.value = val;
  console.log(val, "val");
  await getMaterialCategory();
  canEdit.value = !cannotEdit;
  const houseConstructionMaterialBuyVO = val.house.houseConstructionMaterialBuyVO || [];
  formData.value.tableData = houseConstructionMaterialBuyVO.map((item, index) => {
    return {
      indexs: index,
      ...item,
      contractFile: JSON.parse(item.contractFile || "[]"),
      receiptFile: JSON.parse(item.receiptFile || "[]"),
      paymentFile: JSON.parse(item.paymentFile || "[]"),
    };
  });
}
function handleRCouponDisabled(row) {
  return row.status !== HOUSE_STATUS.APPROVED.value;
}
function handleRowDisabled(row) {
  return row.status === HOUSE_STATUS.APPROVED.value;
}

async function couponSubmit() {
  const validate = await couponRef.value.validate();
  if (!validate) return;
  try {
    await couponApi.audit(couponData.value);
    ElMessage.success("提交成功");
    emit("loadData");
    handleCloseDialog();
    couponCloseDialog();
  } catch (error) {
    console.log("error", error);
  }
}

function couponCloseDialog() {
  couponData.value.couponCode = "";
  dialogCoupon.value = false;
}

function handleEditConsumerCouponBudget(row) {
  couponData.value.linkId = row.id;
  dialogCoupon.value = true;
}

function handleDelete(
  tableData: Array<ConsumerHouseConstructionMaterialInstallForm>,
  index: number
) {
  tableData.splice(index, 1);
}

function handleAdd() {
  let keys;
  if (formData.value.tableData.length === 0) {
    keys = 0;
  } else {
    keys = formData.value.tableData[formData.value.tableData.length - 1].indexs + 1;
  }
  formData.value.tableData.push({
    indexs: keys,
    amount: undefined,
    brandId: undefined,
    brandName: "",
    buyDate: "",
    categoryId: undefined,
    companyId: undefined,
    companyName: "",
    contractFile: [],
    contractTime: "",
    createBy: "",
    createTime: "",
    houseId: currentRow.value.houseId,
    id: undefined,
    merchantUserId: undefined,
    paymentFile: [],
    receiptFile: [],
    remark: "",
    salesman: "",
    salesmanMobile: "",
    status: undefined,
    store: "",
    updateBy: "",
    updateTime: "",
  } as unknown as ConsumerHouseConstructionMaterialBuyForm);
}

function handleChangeBrand(id, row) {
  if (!id) return (row.brandName = "");
  const { brandName } = brandList.value.find((item) => item.id === id);
  row.brandName = brandName;
}

defineExpose({
  showModal,
});
</script>
<style style="scss" scoped>
@import "@/views/house/style/conetr.scss";
:deep(.el-table .cell) {
  overflow: visible !important;
}
.custom-error-message {
  position: absolute;
  bottom: -20px;
  left: 0;
  color: red;
}
.form-container {
  /* //height: 600px; */
  overflow: auto;
}
.form {
  ::v-deep(.el-form-item) {
    margin-bottom: 0;
  }
}
.mult-div {
  width: 800px;
  overflow-x: scroll;
  white-space: nowrap;
  :deep(.el-upload-list--picture-card) {
    flex-wrap: nowrap;
  }
}
</style>
